package com.example.music.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.adapter.SongAdapter;
import com.example.music.db.PlaylistDAO;
import com.example.music.fragment.MyHome;
import com.example.music.model.Song;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PlaylistDetailActivity extends AppCompatActivity {

    private static final String TAG = "PlaylistDetailActivity";

    private long playlistId;
    private String playlistName;
    private RecyclerView recyclerView;
    private SongAdapter adapter;
    private List<Song> songList = new ArrayList<>();
    private PlaylistDAO playlistDao;
    private TextView playlistTitle;
    private TextView songCount;
    private TextView emptyView;
    private ImageView playlistCover;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist_detail);

        // 获取传递过来的歌单ID和名称
        playlistId = getIntent().getLongExtra("playlist_id", -1);
        playlistName = getIntent().getStringExtra("playlist_name");

        // 初始化DAO
        playlistDao = new PlaylistDAO(this);

        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(playlistName != null ? playlistName : "歌单详情");
        }

        // 初始化视图
        playlistTitle = findViewById(R.id.playlist_title);
        songCount = findViewById(R.id.song_count);
        playlistCover = findViewById(R.id.playlist_cover);
        recyclerView = findViewById(R.id.recycler_view);
        emptyView = findViewById(R.id.empty_view);

        // 设置歌单名称
        playlistTitle.setText(playlistName != null ? playlistName : "歌单详情");

        // 设置专辑封面（使用默认或第一个歌曲的封面）
        playlistCover.setImageResource(R.drawable.ic_menu_2);

        // 初始化RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SongAdapter(songList);
        recyclerView.setAdapter(adapter);

        // 加载歌单中的歌曲
        loadSongsInPlaylist();

        // 设置Adapter
        adapter = new SongAdapter(songList);
        adapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Song song) {
                Intent intent = new Intent(PlaylistDetailActivity.this, MusicActivity.class);
                intent.putExtra("position", String.valueOf(songList.indexOf(song)));
                intent.putExtra("songList", new ArrayList<>(songList)); // Pass a copy of the list
                startActivity(intent);
            }
        });

        recyclerView.setAdapter(adapter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新歌曲列表
        loadSongsInPlaylist();
    }

    private void loadSongsInPlaylist() {
        songList.clear();

        if (playlistId == -1) {
            showEmptyView(true);
            updateSongCount();
            return;
        }

        // 获取歌单中的歌曲路径
        List<String> songPaths = playlistDao.getSongsInPlaylist(playlistId);

        Log.d(TAG, "Loaded song paths: " + songPaths);

        if (songPaths.isEmpty()) {
            showEmptyView(true);
            updateSongCount();
            return;
        }

        // 从媒体库加载歌曲信息
        try (Cursor cursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DURATION
                },
                MediaStore.Audio.Media.DATA + " IN (" + makePlaceholders(songPaths.size()) + ")",
                songPaths.toArray(new String[0]),
                null
        )) {
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                    String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                    String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                    String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                    long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                    Song song = new Song(title, artist, album, filePath);
                    song.setDuration(duration);
                    // 获取专辑封面
                    Bitmap albumCover = getAlbumArt(filePath);
                    song.setAlbumCover(albumCover);
                    // 获取歌词文件
                    String lyricsPath = findLyricsFile(filePath);
                    song.setLyricsPath(lyricsPath);

                    songList.add(song);
                    Log.d(TAG, "Added song: " + song.getTitle());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        showEmptyView(songList.isEmpty());
        // 设置专辑封面（使用默认或第一个歌曲的封面）
        if (!songList.isEmpty() && songList.get(0).getAlbumCover() != null) {
            playlistCover.setImageBitmap(songList.get(0).getAlbumCover());
        }

        updateSongCount();
        adapter.updateList(songList);
    }

    private String makePlaceholders(int length) {
        if (length <= 0) {
            return ""; // 如果长度小于等于0，返回空字符串
        }
        StringBuilder sb = new StringBuilder(length * 2);
        for (int i = 0; i < length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append("?");
        }
        return sb.toString();
    }

    private void showEmptyView(boolean show) {
        if (show) {
            recyclerView.setVisibility(View.GONE);
            emptyView.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.VISIBLE);
            emptyView.setVisibility(View.GONE);
        }
    }

    private void updateSongCount() {
        int count = songList.size();
        songCount.setText(count + " 首歌曲");
    }

    private void openAddSongsActivity() {
        Intent intent = new Intent(this, AddSongsToPlaylistActivity.class);
        intent.putExtra("playlist_id", playlistId);
        startActivityForResult(intent, 1); // 请求码为1
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            if (data != null) {
                ArrayList<Song> selectedSongs = data.getParcelableArrayListExtra("selected_songs");
                if (selectedSongs != null) {
                    addSongsToPlaylist(selectedSongs);
                    Toast.makeText(this, "已成功添加 " + selectedSongs.size() + " 首歌曲", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void addSongsToPlaylist(List<Song> songs) {
        for (Song song : songs) {
            playlistDao.addSongToPlaylist(playlistId, song.getPath());
        }
        loadSongsInPlaylist(); // 刷新歌曲列表
    }

    private void playAllSongs() {
        if (songList.isEmpty()) {
            Toast.makeText(this, "歌单中没有歌曲", Toast.LENGTH_SHORT).show();
            return;
        }

        Intent intent = new Intent(PlaylistDetailActivity.this, MusicActivity.class);
        intent.putExtra("position", "0");
        intent.putExtra("songList", new ArrayList<>(songList)); // Pass a copy of the list
        startActivity(intent);
    }

    private void renamePlaylist() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("重命名歌单");

        final EditText input = new EditText(this);
        input.setText(playlistName);
        builder.setView(input);

        builder.setPositiveButton("确定", (dialog, which) -> {
            String newName = input.getText().toString().trim();
            if (!newName.isEmpty() && !newName.equals(playlistName)) {
                if (playlistDao.renamePlaylist(playlistId, newName)) {
                    playlistName = newName;
                    playlistTitle.setText(playlistName);
                    Toast.makeText(this, "歌单已重命名", Toast.LENGTH_SHORT).show();
                }
            }
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    private void deletePlaylist() {
        new AlertDialog.Builder(this)
                .setTitle("删除歌单")
                .setMessage("确定要删除 '" + playlistName + "' 歌单吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    if (playlistDao.deletePlaylist(playlistId)) {
                        Toast.makeText(this, "歌单已删除", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_playlist_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_play_all) {
            playAllSongs();
            return true;
        } else if (id == R.id.action_rename_playlist) {
            renamePlaylist();
            return true;
        } else if (id == R.id.action_delete_playlist) {
            deletePlaylist();
            return true;
        } else if (id == R.id.action_add_song) {
            openAddSongsActivity();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }
    private String findLyricsFile(String songFilePath) {
        File songFile = new File(songFilePath);
        File directory = songFile.getParentFile();
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            return null;
        }

        FilenameFilter lrcFilter = (dir, name) -> name.equalsIgnoreCase(songFile.getName().replace(".mp3", ".lrc"));
        File[] lrcFiles = directory.listFiles(lrcFilter);

        if (lrcFiles != null && lrcFiles.length > 0) {
            return lrcFiles[0].getAbsolutePath();
        }

        return null;
    }
}